package com.bb.blog.code.threading.example;


import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 按照正常逻辑只会有  1,1  0,1  1,0
 * 但是会有几率出现CPU指令重排 出现结果（0,0）
 *
 */
public class ValidateReOrderExample {
    private static int x = 0;
    private static int y = 0;
    private static volatile int a = 0;
    private static volatile int b = 0;
    public static void main(String[] args) throws InterruptedException {
        Unsafe theUnsafe = getUnsafe();
        for (int i = 0;  ; i++) {
            a= 0;
            b=0;
            x=0;
            y=0;
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
//
                    a = 1;
//                    getUnsafe().loadFence();
                    x = b;
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
//                    getUnsafe().loadFence();
                    y = a;
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            if (x == 0 && y == 0) {
                System.out.println("i:  " + i + "   x:" + x + "  y:" +  y + "   a:" + a + "  b:" + b);
                System.err.println("err");
                break;
            } else {
                System.out.println("i:  " + i + "   x:" + x + "  y:" +  y + "   a:" + a + "  b:" + b);
            }
        }
    }
    public static  Unsafe getUnsafe(){
        try{
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            Unsafe theUnsafe = (Unsafe) field.get(null);
            return theUnsafe;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
